package com.huatech.cloud.filter;

import java.security.PublicKey;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.alibaba.druid.filter.FilterAdapter;
import com.alibaba.druid.filter.config.ConfigTools;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.proxy.jdbc.DataSourceProxy;

import lombok.extern.slf4j.Slf4j;

@Slf4j
//@Component
public class DruidDataSourceFilter extends FilterAdapter {
    
	
    @Value("${crypto.public-key}")
    private String decryptKey;
	
    @Override
    public void init(DataSourceProxy dataSourceProxy) {
		if (!(dataSourceProxy instanceof DruidDataSource)) {
            log.error("ConfigLoader only support DruidDataSource");
            return;
        }

        DruidDataSource dataSource = (DruidDataSource) dataSourceProxy;
        // 判断是否需要解密，如果需要就进行解密行动
        if (isNotEmpty(decryptKey)) {
            decrypt(dataSource);
        }
    }
	
    public void decrypt(DruidDataSource dataSource) {

        try {
            String encryptedUsername = null, encryptedPassword = null;
           
            if (encryptedUsername == null || encryptedUsername.length() == 0) {
            	encryptedUsername = dataSource.getUsername();
            }
            
            if (encryptedPassword == null || encryptedPassword.length() == 0) {
                encryptedPassword = dataSource.getPassword();
            }

            PublicKey publicKey =  ConfigTools.getPublicKey(decryptKey);

            String usernamePlainText = ConfigTools.decrypt(publicKey, encryptedUsername);
            String passwordPlainText = ConfigTools.decrypt(publicKey, encryptedPassword);

            dataSource.setUsername(usernamePlainText);
            dataSource.setPassword(passwordPlainText);
            
        } catch (Exception e) {
            throw new IllegalArgumentException("Failed to decrypt.", e);
        }
    }
    
    public boolean isNotEmpty(String source) {
    	return source != null && !"".equals(source.trim());
    }
	
}
